package com.neusoft.elmboot.service.impl;

import com.neusoft.elmboot.mapper.UserMapper;
import com.neusoft.elmboot.po.User;
import com.neusoft.elmboot.service.PointsService;
import com.neusoft.elmboot.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Service
public class PointsServiceImpl implements PointsService {
	
	@Autowired
	private UserMapper userMapper;
	
	@Autowired
	private UserService userService;
	
	@Override
	@Transactional
	public int addPointsFromPayment(String userId, Double amount) {
		if (amount == null || amount <= 0) {
			return 0;
		}
		
		// 四舍五入计算积分：1元 = 1积分
		BigDecimal amountDecimal = BigDecimal.valueOf(amount);
		int pointsEarned = amountDecimal.setScale(0, RoundingMode.HALF_UP).intValue();
		
		// 获取用户当前信息
		User user = userService.getUserInfoById(userId);
		if (user == null) {
			return 0;
		}
		
		// 检查是否为超级会员且未过期
		boolean isSuperMember = checkSuperMemberStatus(user);
		if (isSuperMember) {
			// 超级会员双倍积分和经验值
			pointsEarned = pointsEarned * 2;
		}
		
		// 更新积分和经验值（经验值等于积分）
		int currentPoints = user.getPoints() != null ? user.getPoints() : 0;
		int currentXP = user.getExperiencePoints() != null ? user.getExperiencePoints() : 0;
		
		int newPoints = currentPoints + pointsEarned;
		int newXP = currentXP + pointsEarned; // 经验值等于积分
		
		// 更新积分和经验值
		userMapper.updatePointsAndXP(userId, newPoints, newXP);
		
		// 更新等级和折扣
		updateUserLevelAndDiscount(userId);
		
		return pointsEarned;
	}
	
	@Override
	@Transactional
	public void addPointsFromComment(String userId, int points) {
		if (points <= 0) {
			return;
		}
		// 获取用户当前信息
		User user = userService.getUserInfoById(userId);
		if (user == null) {
			return;
		}
		int currentPoints = user.getPoints() != null ? user.getPoints() : 0;
		int newPoints = currentPoints + points;
		// 仅更新积分，不修改经验值
		userMapper.updatePoints(userId, newPoints);
	}
	
	@Override
	public int calculateLevel(Integer experiencePoints) {
		if (experiencePoints == null) {
			experiencePoints = 0;
		}
		
		if (experiencePoints < 500) {
			return 1;
		} else if (experiencePoints < 2000) {
			return 2;
		} else if (experiencePoints < 5000) {
			return 3;
		} else if (experiencePoints < 20000) {
			return 4;
		} else {
			return 5;
		}
	}
	
	@Override
	public int getDiscountByLevel(int level) {
		switch (level) {
			case 1:
				return 99; // 99折
			case 2:
				return 98; // 98折
			case 3:
				return 96; // 96折
			case 4:
				return 94; // 94折
			case 5:
				return 92; // 92折
			default:
				return 99;
		}
	}
	
	@Override
	@Transactional
	public void updateUserLevelAndDiscount(String userId) {
		User user = userService.getUserInfoById(userId);
		if (user == null) {
			return;
		}
		
		int xp = user.getExperiencePoints() != null ? user.getExperiencePoints() : 0;
		int level = calculateLevel(xp);
		int discount = getDiscountByLevel(level);
		
		userMapper.updateLevelAndDiscount(userId, level, discount);
	}
	
	@Override
	@Transactional
	public boolean redeemPoints(String userId, int points) {
		if (points <= 0) {
			return false;
		}
		
		User user = userService.getUserInfoById(userId);
		if (user == null) {
			return false;
		}
		
		int currentPoints = user.getPoints() != null ? user.getPoints() : 0;
		if (currentPoints < points) {
			return false; // 积分不足
		}
		
		// 扣除积分（经验值不减少）
		int newPoints = currentPoints - points;
		userMapper.updatePoints(userId, newPoints);
		
		return true;
	}
	
	@Override
	public User getUserPointsInfo(String userId) {
		return userService.getUserInfoById(userId);
	}
	
	/**
	 * 检查用户是否为有效的超级会员
	 */
	private boolean checkSuperMemberStatus(User user) {
		if (user.getIsSuperMember() == null || user.getIsSuperMember() == 0) {
			return false;
		}
		
		if (user.getSuperMemberExpireTime() == null || user.getSuperMemberExpireTime().isEmpty()) {
			return false;
		}
		
		try {
			DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
			LocalDateTime expireTime = LocalDateTime.parse(user.getSuperMemberExpireTime(), formatter);
			return LocalDateTime.now().isBefore(expireTime);
		} catch (Exception e) {
			return false;
		}
	}
}

